import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { constantRoutes } from "@/router";
import { resetRouter } from "@/router";

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes,
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token; // 存储到vuex
    setToken(token); // 持久化本地 cookie
  },
  removeToken(state) {
    state.token = null;
    removeToken();
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  serUserInfo(state, userInfo) {
    state.userInfo = userInfo;
  },
  removeUserInfo(state) {
    state.userInfo = {};
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes];
  },
};

// vuex中约定异步走actions
const actions = {
  // user login
  async login({ commit }, userInfo) {
    // 调接口传递数据给后台
    const token = await login(userInfo);
    commit("SET_TOKEN", token);
  },

  // get user info
  async getInfo({ commit, state }) {
    const userInfo = await getInfo();
    commit("serUserInfo", userInfo);
    return userInfo;
  },

  // user logout
  logout({ commit, state }) {
    commit("removeUserInfo");
    commit("removeToken");
    resetRouter();
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken(); // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
